package com.cqu.springmvc.servlet;
import com.cqu.springmvc.annotation.*;
import com.cqu.springmvc.context.WebApplicationContext;
import com.cqu.springmvc.exception.ContextException;
import com.cqu.springmvc.handler.MvcHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.cqu.springmvc.annotation.Controller;
import com.cqu.springmvc.annotation.RequestMapping;
import com.cqu.springmvc.annotation.RequestParm;
import com.cqu.springmvc.annotation.Service;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DispatcherServlet extends HttpServlet {

    private WebApplicationContext webApplicationContext;
    //存储 URL 和对象的方法映射关系
    List<MvcHandler> handlerList = new ArrayList<MvcHandler>();

    @Override
    public void init() throws ServletException {
        //1.Servlet初始化的时候，读取初始化的参数
        String contextConfigLocation = this.getServletConfig().getInitParameter("contextConfigLocation");
        //2.创建Spring容器
        webApplicationContext = new WebApplicationContext(contextConfigLocation);
        //3.初始化Spring容器
        webApplicationContext.refresh();
        //4.初始化请求映射  /file/upload ----> Controller ----> method ----> parameter
        initHandleMapping();
        System.out.println("请求地址和控制器方法的映射关系:"+handlerList);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //进行请求的分发处理
        try {
            excuteDispatch(req, resp);
        } catch (InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    //初始化请求映射
    private void initHandleMapping() {
        //判断IOCMap中是否有bean对象
        if(webApplicationContext.iocMap.isEmpty()) {
            throw new ContextException("Spring容器为空!");
        }
        for(Map.Entry<String,Object> entry : webApplicationContext.iocMap.entrySet()) {
            Class<?> classzz = entry.getValue().getClass();
            if(classzz.isAnnotationPresent(Controller.class)) {
                Method[] declaredMethods= classzz.getDeclaredMethods();
                for(Method declaredMethod : declaredMethods) {
                    if(declaredMethod.isAnnotationPresent(RequestMapping.class)) {
                        RequestMapping requestMappingAnnotation = declaredMethod.getAnnotation(RequestMapping.class);
                        //  /file/upload
                        String url = requestMappingAnnotation.value();
                        MvcHandler handler = new MvcHandler(url,entry.getValue(),declaredMethod);
                        handlerList.add(handler);
                    }
                }
             }
        }
    }

    //进行请求的分发处理
    private void excuteDispatch(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException {
        MvcHandler handler = getHandler(req);
        try {
            if(handler == null) {
                resp.getWriter().print("<h1>404 NOT FOUND!</h1>");
            } else {
                Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
                //定义一个参数的数组集合
                Object[] params = new Object[parameterTypes.length];
                for(int i=0; i<parameterTypes.length; i++) {
                    Class<?> parameterType = parameterTypes[i];
                    if("HttpServletRequest".equals(parameterType.getSimpleName())){
                        params[i] = req;
                    } else if("HttpServletResponse".equals(parameterType.getSimpleName())) {
                        params[i] = resp;
                    }
                }
                if(handler.getController().getClass().getSimpleName().equals("FileController")) {
                    List<Part> parts = (List<Part>) req.getParts();
                    //获取请求中的参数集合
                    String name = "files";
                    int index = hasRequestParm(handler.getMethod(), name);
                    if(index != -1) {
                        params[index] = parts;
                    } else {
                        List<String> names = getParameterNames(handler.getMethod());
                        System.out.println("参数集合:" + names);
                        for (int i = 0; i < names.size(); i++) {
                            if (name.equals(names.get(i))) {
                                params[i] = parts;
                            }
                        }
                    }

                } else if(handler.getController().getClass().getSimpleName().equals("UserController")) {
                    //获取请求中的参数集合
                    Map<String, String[]> parameterMap = req.getParameterMap();
                    for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                        String name = entry.getKey();
                        String value = entry.getValue()[0];
                        System.out.println("请求参数:"+name+"----"+value);
                        //判断控制器方法的参数是否有RequestParm注解并找到对应的value值
                        //如果找到value值，则返回这个参数的下标；没有找到则返回-1
                        int index = hasRequestParm(handler.getMethod(), name);
                        if(index != -1) {
                            params[index] = value;
                        } else {
                            List<String> names = getParameterNames(handler.getMethod());
                            System.out.println("参数集合:"+names);
                            for(int i=0; i< names.size(); i++) {
                                if(name.equals(names.get(i))) {
                                    params[i] = value;
                                }
                            }
                        }
                    }
                }

                //调用控制器中的方法
                Object result = handler.getMethod().invoke(handler.getController(), params);
                if(result instanceof String) { //返回字符串
                    //跳转jsp
                    String viewName = (String)result;
                    //forward:/file.jsp
                    if(viewName.contains(":")) {
                        String viewtype = viewName.split(":")[0];
                        String viewPage = viewName.split(":")[1];
                        if(viewtype.equals("forward")) {
                            req.getRequestDispatcher(viewPage).forward(req,resp);
                        } else {
                            //redirect:/file.jsp
                            resp.sendRedirect(viewPage);
                        }
                    } else { //默认转发 /file.jsp
                        req.getRequestDispatcher(viewName).forward(req,resp);
                    }
                } else { //返回json数据
                    if(handler.getMethod().isAnnotationPresent(ResponseBody.class)) {
                        //把返回值转换为JSON字符串
                        ObjectMapper objectMapper = new ObjectMapper();
                        String json = objectMapper.writeValueAsString(result);
                        resp.setContentType("text/html;charset=utf-8");
                        PrintWriter out = resp.getWriter();
                        out.print(json);
                        out.flush();
                        out.close();
                    }
                }
            }
        } catch (IOException | ServletException e) {
            e.printStackTrace();
        }
    }

    //获取请求对应的handler
    public MvcHandler getHandler(HttpServletRequest req) {
        String requestURI = req.getRequestURI(); //  /file/upload
        for(MvcHandler mvcHandler: handlerList) {
            if(mvcHandler.getUrl().equals(requestURI)){
                return mvcHandler;
            }
        }
        return null;
    }

    //判断控制器方法的参数是否有RequestParm注解并找到对应的value值
    //如果找到value值，则返回这个参数的下标；没有找到则返回-1
    public int hasRequestParm(Method method, String name) {
        Parameter[] parameters = method.getParameters();
        for(int i=0; i<parameters.length; i++) {
            Parameter parameter = parameters[i];
            boolean flag = parameter.isAnnotationPresent(RequestParm.class);
            if(flag) {
                RequestParm requestParm = parameter.getAnnotation(RequestParm.class);
                String requestParmValue = requestParm.value();
                if(name.equals(requestParmValue)) {
                    return i;
                }
            }
        }
        return -1;
    }

    //获取控制器方法的参数的名字
    public List<String> getParameterNames(Method method) {
        List<String> parameterNamesList = new ArrayList<String>();
        Parameter[] parameters = method.getParameters();
        for(Parameter parameter : parameters) {
            parameterNamesList.add(parameter.getName());
        }
        return parameterNamesList;
    }



}
